const drag = {
    beforeMount(el) {
        el.style.cursor = "move";

        el.onmousedown = (e) => {
            if (e.currentTarget !== e.target) return;
            const mouseX = e.clientX;
            const mouseY = e.clientY;
            const domX = el.offsetLeft;
            const domY = el.offsetTop;
            const maxX = document.body.clientWidth - el.offsetWidth;
            const maxY = document.documentElement.clientHeight - el.offsetHeight;

            document.onmousemove = function (e) {
                const deltaX = e.clientX - mouseX;
                const deltaY = e.clientY - mouseY;
                let newX = domX + deltaX;
                let newY = domY + deltaY;

                //边界控制
                if (newX < 0) newX = 0;
                else if (newX > maxX) newX = maxX;
                if (newY < 0) newY = 0;
                else if (newY > maxY) newY = maxY;

                el.style.left = newX + "px";
                el.style.top = newY + "px";
            };

            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            };
            return false;
        };
    },
};

const directives = {
    install: function (app) {
        app.directive("drag", drag);
    },
};
export default directives;
